package repositoryimpl

import (
	"github.com/astaxie/beego/orm"

	"cvevulner/cve-ddd/domain"
	"cvevulner/models"
)

const (
	fieldStatus  = "status"
	fieldBranch  = "branch"
	fieldCollect = "collect_date"
)

func (impl repositoryImpl) AddCallback(callback domain.Callback) error {
	c := toCallbackModels(callback)

	_, err := orm.NewOrm().Insert(&c)

	return err
}

func (impl repositoryImpl) UpdateCallback(callback domain.Callback) error {
	c := toCallbackModels(callback)

	_, err := orm.NewOrm().Update(&c)

	return err
}

func (impl repositoryImpl) GetProcessingCallback() ([]domain.Callback, error) {
	c := new(models.CollectCallback)
	var modelCallback []models.CollectCallback

	_, err := orm.NewOrm().QueryTable(c).Filter(fieldStatus, domain.StatusProcessing).All(&modelCallback)
	if err != nil {
		return nil, err
	}

	var callback []domain.Callback
	for _, v := range modelCallback {
		t := toCallback(v)

		callback = append(callback, t)
	}

	return callback, nil
}

func (impl repositoryImpl) SaveCollectResult(r domain.CollectResult) error {
	resultDO := models.CollectResult{
		Branch:      r.Branch,
		CollectDate: r.Date,
		Result:      r.Result,
	}

	_, err := orm.NewOrm().Insert(&resultDO)

	return err
}

func (impl repositoryImpl) FindCollectResult(branch, collectDate string) (string, error) {
	callbackResult := new(models.CollectResult)

	query := orm.NewOrm().QueryTable(callbackResult)
	if branch != "" {
		query = query.Filter(fieldBranch, branch)
	}

	if collectDate != "" {
		query = query.Filter(fieldCollect, collectDate)
	}

	err := query.One(callbackResult)
	if err != nil {
		return "", err
	}

	return callbackResult.Result, nil
}

func toCallbackModels(callback domain.Callback) models.CollectCallback {
	return models.CollectCallback{
		Id:          callback.Id,
		Branch:      callback.Branch,
		Status:      callback.Status,
		CollectDate: callback.Date,
		CallbackId:  callback.CallbackId,
	}
}

func toCallback(m models.CollectCallback) domain.Callback {
	return domain.Callback{
		Id:         m.Id,
		Branch:     m.Branch,
		Status:     m.Status,
		Date:       m.CollectDate,
		CallbackId: m.CallbackId,
	}
}
